//
//  UITextView+Limit.m
//  Commom
//
//  Created by Clavis on 2019/12/7.
//

#import "UITextView+Limit.h"
#import <objc/runtime.h>

@interface UITextView ()

@property (nonatomic, assign) BOOL isAlreadyAddNotification;
@property (nonatomic, assign) SEGInputLimitStyle limitStyle; /// 限制输入的类型

@end

@implementation UITextView (Limit)

- (void)setLimitStyle:(SEGInputLimitStyle)limitStyle {
    objc_setAssociatedObject(self, @selector(limitStyle), @(limitStyle), OBJC_ASSOCIATION_COPY);
    [self.undoManager disableUndoRegistration];
    [self addNotification];
}

- (SEGInputLimitStyle)limitStyle {
     return [objc_getAssociatedObject(self, _cmd) integerValue];
}

- (void)setLimitInputMaxLength:(NSInteger)limitInputMaxLength {
    objc_setAssociatedObject(self, @selector(limitInputMaxLength), @(limitInputMaxLength), OBJC_ASSOCIATION_COPY);
    [self.undoManager disableUndoRegistration];
    [self addNotification];
}

- (void)setIsAlreadyAddNotification:(BOOL)isAlreadyAddNotification {
    objc_setAssociatedObject(self, @selector(isAlreadyAddNotification), @(isAlreadyAddNotification), OBJC_ASSOCIATION_COPY);
}

- (BOOL)isAlreadyAddNotification {
    return [objc_getAssociatedObject(self, _cmd) boolValue];
}

- (NSInteger)limitInputMaxLength {
    return [objc_getAssociatedObject(self, _cmd) integerValue];
}

- (void)addNotification {
    if (!self.isAlreadyAddNotification) {
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleTextDidChange:) name:UITextViewTextDidChangeNotification object:nil];
        self.isAlreadyAddNotification = YES;
    }
}

- (void)handleTextDidChange:(NSNotification *)notification {

    if (notification.object != self) {
        return;
    }
    
    // 先进行长度过滤
    UITextView *textView = self;
    if (self.limitInputMaxLength) {
        BOOL isEnteringChinese = NO; // 是否正在输入中文
        NSString *lang = textView.textInputMode.primaryLanguage;
        if ([lang isEqualToString:@"zh-Hans"]) {// 简体中文输入，包括简体拼音，健体五笔，简体手写
           UITextRange *selectedRange = [textView markedTextRange];
           //获取高亮部分
           UITextPosition *position = [textView positionFromPosition:selectedRange.start offset:0];

           //没有高亮选择的字，则对已输入的文字进行字数统计和限制
           if (!position || !selectedRange) {
           } else {
               isEnteringChinese = YES;
           }
        }
                   
        // 限制输入长度
        NSLog(@"🌙🌙🌙🌙 %ld %@", self.text.length, self.text);
        if (self.limitInputMaxLength > 0 && !isEnteringChinese) {
            if (textView.text.length > self.limitInputMaxLength) {
                textView.text = [textView.text substringToIndex:self.limitInputMaxLength];
                NSLog(@"🌙🌙🌙🌙 limit = %@", self.text);
            }
        }
    }
    
    if (self.limitStyle == SEGInputLimitStyleNone) {
        return;
    }
    
    UITextView *textField = self;
    dispatch_async(dispatch_get_main_queue(), ^{
          NSString *lang = textField.textInputMode.primaryLanguage;
        if ([lang isEqualToString:@"zh-Hans"]) {// 简体中文输入，包括简体拼音，健体五笔，简体手写
            UITextRange *selectedRange = [textField markedTextRange];
            //获取高亮部分
            UITextPosition *position = [textField positionFromPosition:selectedRange.start offset:0];
        
            //没有高亮选择的字，则对已输入的文字进行字数统计和限制
            if (!position || !selectedRange) {
                textField.text = [self fliterString:self.text];
            }
            //有高亮选择的字符串，则暂不对文字进行统计和限制
            else{
                // 高亮部分包含特殊字符 则过滤
                
                NSString *changeText = self.text;
                // 这里过滤的不是空格 是中文输入的特殊符号
                NSString *flitterString = [changeText stringByReplacingOccurrencesOfString:@" " withString:@""];
                NSString *legalString  = [self fliterString:flitterString];
                
                if (![flitterString isEqualToString:legalString]) {
                    NSLog(@"【%@】 ---  [%@]  ---  [%@]", changeText, flitterString, legalString);
                    textField.text = legalString;
                }
            }
        }
        // 中文输入法以外的直接对其统计限制即可，不考虑其他语种情况
        else{
            textField.text = [self fliterString:self.text];
        }
    
     });
    
}

- (NSString *)fliterString:(NSString *)str {
    
//    NSString *pattern = @"[a-zA-Z0-9\u4E00-\u9FA5]+";
//    NSString *pattern = @"[a-zA-Z0-9]+";
    NSString *pattern = [self getCurrentPattern];
    
    NSError *error = nil;
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:pattern options:NSRegularExpressionCaseInsensitive error:&error];

    NSArray<NSTextCheckingResult *> *result = [regex matchesInString:str options:0 range:NSMakeRange(0, str.length)];
    NSMutableString *resultString = [NSMutableString string];
    if (result) {
        for (int i = 0; i<result.count; i++) {
            NSTextCheckingResult *res = result[i];
            NSLog(@"str == %@", [str substringWithRange:res.range]);
            [resultString appendString:[str substringWithRange:res.range]];
        }
    }else{
        NSLog(@"error == %@",error.description);
    }
     
    return  resultString;
}

- (NSString *)getCurrentPattern {
    switch (self.limitStyle) {
        case SEGInputLimitStyleNone:
            return @"";
            
//        case SEGInputLimitStyleNoChinese:
//            // ???
//            return @"[\u4E00-\u9FA5]+";
        
        case SEGInputLimitStyleNoSymbol:
            return @"[a-zA-Z0-9\u4E00-\u9FA5]+";
        
        case SEGInputLimitStyleNoClineseNoSymbol:
            return @"[a-zA-Z0-9]+";
        
        case SEGInputLimitStyleAllowNumber:
            return @"[0-9]+";
        default:
            break;
    }
    return @"[a-zA-Z0-9\u4E00-\u9FA5]+";
}


@end
